from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import resolve
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from real_estate.forms import PropertyForm
from real_estate.models import Property, Transfer, Rental, Listing
from real_estate.utils import get_property_type_code
from settings import DEFAULT_PER_PAGE, DEFAULT_SORT_FIELD

UNLIMIT = 'unlimit'

SORT_BY_ADDRESS = 'address'
SORT_BY_SALE_PRICE = 'sale_price'
SORT_BY_SALE_DATE = 'sale_date'
SORT_BY_LOT_PLAN = 'lot_plan'
SORT_BY_ZONING = 'zoning'
SORT_BY_CATEGORY = 'category'
SORT_BY_LAND_USE = 'land_use'
SORT_BY_BEDROOM = 'bedroom'
SORT_BY_BATHROOM = 'bathroom'
SORT_BY_CAR_SPACE = 'car_space'
SORT_BY_LAND_SIZE = 'land_size'

def index(request, mode='property', state_slug=None, city_slug=None, suburb_slug=None, street_slug=None, postcode=None,
    property_type=None, bedroom=None, bathroom=None, car_space=None, min_land_size=None, max_land_size=None,
    max_sale_price=None, min_sale_price=None, template_name="property/index.html"):

    try:
        params = resolve(request.path_info).kwargs
    except :
        params = {}

    properties = get_properties_by_mode(mode)

    if not is_empty(state_slug):
        properties = properties.filter(street__suburb__city__state__slug=state_slug)
    if not is_empty(city_slug):
        properties = properties.filter(street__suburb__city__slug=city_slug)
    if not is_empty(suburb_slug):
        properties = properties.filter(street__suburb__slug=suburb_slug)
    if not is_empty(street_slug):
        properties = properties.filter(street__slug=street_slug)
    if not is_empty(postcode):
        properties = properties.filter(street__suburb__postcode=postcode)


    if not is_empty(property_type):
        properties = properties.filter(type__in=get_property_type_code(property_type.split('_')))
    if not is_empty(bedroom):
        properties = properties.filter(bedroom__in=bedroom.split('_'))
    if not is_empty(bathroom):
        properties = properties.filter(bathroom__in=bathroom.split('_'))
    if not is_empty(car_space):
        properties = properties.filter(car_space__in=car_space.split('_'))
    if not is_empty(max_land_size):
        properties = properties.filter(land_area__lte=max_land_size)
    if not is_empty(min_land_size):
        properties = properties.filter(land_area__gte=min_land_size)
#    if not is_empty(max_sale_price):
#        properties = properties.filter(sale_price__lte=max_sale_price)
#    if not is_empty(min_land_size):
#        properties = properties.filter(sale_price__gte=min_sale_price)

    sort = get_sorting(request)
    properties = sort_properties(properties, sort)

    property_form = PropertyForm()

    limit = get_limit(request)
    paginator = Paginator(properties, limit)
    page = get_current_page(request)

    try:
        properties = paginator.page(page)
    except (EmptyPage, InvalidPage):
        properties = paginator.page(paginator.num_pages)

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))


    return properties

####################################################################################################

def get_property_type(property_type):
    return [0, 2, 3]

def is_empty(field):
    return (field is None) or (field == UNLIMIT)

def get_property_form(request):
    if request.method == 'GET':
        property_form = PropertyForm(request.GET)
    else:
        property_form = PropertyForm()

    property_form.is_valid()

    return property_form

def get_current_page(request):
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
        
    return page

def get_limit(request):
    try:
        limit = int(request.GET.get('limit', DEFAULT_PER_PAGE))
    except ValueError:
        limit = int(DEFAULT_PER_PAGE)
    return limit

def get_sorting(request):
    try:
        sort = request.GET.get('sort', DEFAULT_SORT_FIELD)
    except ValueError:
        sort = DEFAULT_SORT_FIELD
    return sort

def get_properties_by_mode(mode):
    if mode=='property':
        properties = Property.objects.select_related('street', 'street__suburb', 'street__suburb__city')
    elif mode=='transfer':
        properties = Transfer.objects.select_related('street', 'street__suburb', 'street__suburb__city')
    elif mode=='rental':
        properties = Rental.objects.select_related('street', 'street__suburb', 'street__suburb__city')
    elif mode=='listing':
        properties = Listing.objects.select_related('street', 'street__suburb', 'street__suburb__city')
    else:
        properties = Property.objects

    return properties

def sort_properties(properties, sort):
    if sort==SORT_BY_ADDRESS:
        properties = properties.order_by('street_number', '-street__name')
    elif sort==SORT_BY_BATHROOM:
        properties = properties.order_by('bathroom')
    elif sort==SORT_BY_BEDROOM:
        properties = properties.order_by('bedroom')
    elif sort==SORT_BY_CAR_SPACE:
        properties = properties.order_by('car_space')
    elif sort==SORT_BY_CATEGORY:
        properties = properties.order_by('type')
    elif sort==SORT_BY_ZONING:
        properties = properties.order_by('zone_code')
    elif sort==SORT_BY_LAND_SIZE:
        properties = properties.order_by('land_area')
    elif sort==SORT_BY_LAND_USE:
        properties = properties.order_by('primary_use')
    else:
        properties = properties.order_by('street_number', '-street__name')

    return properties